package com.jh.jutil.worker;


import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author namhh
 */
public abstract class Pool {

    private static final int _corePoolSize = 10;
    private static final int _maxPoolSize = 18;
    private static final long _keepAliveTime = 5000;

    private final ThreadPoolExecutor _threadPoolExecutor
            = new ThreadPoolExecutor(
                    _corePoolSize,
                    _maxPoolSize,
                    _keepAliveTime,
                    TimeUnit.MILLISECONDS,
                    new ArrayBlockingQueue(5000)
            );

    public void excute(Job job) {
        _threadPoolExecutor.execute(job);
    }

    public Pool setRejectedExecutionHandler(final long timeout) {
        _threadPoolExecutor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                try {
                    Thread.sleep(timeout);
                    executor.execute(r);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
        return this;
    }

    public void shutdown(long timeOutBySecond) {
        try {
            _threadPoolExecutor.shutdown();
            _threadPoolExecutor.awaitTermination(timeOutBySecond, TimeUnit.SECONDS);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }

}
